/*
 * @lc app=leetcode.cn id=661 lang=cpp
 *
 * [661] 图片平滑器
 */

// @lc code=start
class Solution
{
public:
  vector<vector<int>> adj = {
      {-1, 0},
      {1, 0},
      {0, -1},
      {0, 1},
      {-1, -1},
      {-1, 1},
      {1, 1},
      {1, -1}};
  int M, N;
  vector<vector<int>> imageSmoother(vector<vector<int>>& img)
  {
    M = img.size(), N = img[0].size();
    vector<vector<int>> ans(M, vector<int>(N));
    for (int i = 0; i < M; ++i) {
      for (int j = 0; j < N; ++j) {
        int pix_cnt = 1;
        int pix_sum = img[i][j];
        for (auto& d : adj) {
          int x = i + d[0];
          int y = j + d[1];
          if (IsLegal(x, y)) {
            ++pix_cnt;
            pix_sum += img[x][y];
          }
        }
        ans[i][j] = pix_sum / pix_cnt;
      }
    }
    return ans;
  }

  bool IsLegal(int r, int c)
  {
    return r >= 0 && r < M && c >= 0 && c < N;
  }
};
// @lc code=end
